package com.mixsmart.commonweb.helper;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.mixsmart.commonweb.IWebConstant;
import com.mixsmart.commonweb.bean.UserInfo;
import com.mixsmart.utils.StringUtils;

/**
 * HttpRequest助手
 * @author lmq
 * @version 1.0
 * @since JDK版本大于等于1.6
 * 2016年1月25日
 */
public class HttpRequestHelper implements IWebConstant {

	private static final Logger logger = Logger.getLogger(HttpRequestHelper.class);
	
	/**
	 * 获取当前URI(不含参数)
	 * @param request HTTP请求对象
	 * @return 返回当前URI
	 */
	public static String getCurrentUri(HttpServletRequest request) {
		String contextPath = request.getContextPath();
		String currentUri = request.getRequestURI();
		contextPath = contextPath+"/";
		currentUri = currentUri.substring(contextPath.length(), currentUri.length());
		logger.debug("当前请求的URI为:"+currentUri);
		return currentUri;
	}
	
	/**
	 * 获取当前URI(带参数)
	 * @param request HTTP请求对象
	 * @return 返回当前URI
	 */
	public static String getCurrentUriParam(HttpServletRequest request) {
		String contextPath = request.getContextPath();
		String currentUri = request.getRequestURI();
		contextPath = contextPath+"/";
		currentUri = currentUri.substring(contextPath.length(), currentUri.length());
		if(StringUtils.isNotEmpty(request.getQueryString())) {
			currentUri +="?"+request.getQueryString();
		}
		try {
			currentUri = URLDecoder.decode(currentUri, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		logger.debug("当前请求的URI为:"+currentUri);
		return currentUri;
	}
	
	/**
	 * 设置session值
	 * @param request HTTP请求对象
	 * @param key 名称
	 * @param value 存放到session中的值
	 */
	public static void setSession(HttpServletRequest request,String key,Object value) {
		HttpSession session = request.getSession();
		if(null != session) {
			session.setAttribute(key, value);
		}
		session = null;
	}
	
	/**
	 * 获取session值
	 * @param request HTTP请求对象
	 * @param key 存放在session中的名称
	 * @return 返回对象
	 */
    public static Object getSession(HttpServletRequest request,String key) {
    	HttpSession session = request.getSession();
    	Object obj = null;
		if(null != session) {
			obj = session.getAttribute(key);
		}
		session = null;
		return obj;
	}
    
    /**
	 * 添加用户信息到session
	 * @param session HttpSession对象
	 * @param userInfo 用户信息
	 */
	public static void setUserInfo2Session(HttpSession session,UserInfo userInfo) {
		if(null != session) {
			session.setAttribute(IWebConstant.SESSION_USER_KEY, userInfo);
		}
	}
	
	/**
	 * 从session中获取用户信息
	 * @param session HttpSession对象
	 * @return 返回用户信息
	 */
    public static UserInfo getUserInfoFromSession(HttpSession session) {
    	UserInfo userInfo = null;
    	if(null != session) {
    		userInfo = (UserInfo)session.getAttribute(IWebConstant.SESSION_USER_KEY);
    	}
    	return userInfo;
	}
    
    /**
	 * 添加用户信息到session
	 * @param request HTTP请求对象
	 * @param userInfo 用户信息对象
	 */
	public static void setUserInfo2Session(HttpServletRequest request,UserInfo userInfo) {
		if(null != request) {
			setUserInfo2Session(request.getSession(),userInfo);
		}
	}
	
	/**
	 * 从session中获取用户信息
	 * @param request HTTP请求对象
	 * @return 返回用户信息对象
	 */
    public static UserInfo getUserInfoFromSession(HttpServletRequest request) {
    	UserInfo userInfo = null;
    	if(null != request) {
    		userInfo = (UserInfo)request.getSession().getAttribute(IWebConstant.SESSION_USER_KEY);
    	}
    	return userInfo;
	}
	
    /**
     * 获取客户端IP地址
     * 多个IP地址之间用英文逗号“,”隔开
     * @param request HTTP请求对象
     * @return 返回IP地址
     */
    public static String getClientAddr(HttpServletRequest request) {
    	String ipAddress = request.getHeader("x-forwarded-for");   
        if(ipAddress == null || ipAddress.length() == 0 
        		|| "unknown".equalsIgnoreCase(ipAddress)) {   
        	ipAddress = request.getHeader("Proxy-Client-IP");   
        }   
        if(ipAddress == null || ipAddress.length() == 0 
        		|| "unknown".equalsIgnoreCase(ipAddress)) {   
            ipAddress = request.getHeader("WL-Proxy-Client-IP");   
        }   
        if(ipAddress == null || ipAddress.length() == 0 
        		|| "unknown".equalsIgnoreCase(ipAddress)) {   
	        ipAddress = request.getRemoteAddr();   
	        if(ipAddress.equals("127.0.0.1")) {
	        	//根据网卡取本机配置的IP 
	        	InetAddress inet=null;
	        	try {
	        		inet = InetAddress.getLocalHost();
	        	} catch (UnknownHostException e) { 
	        		e.printStackTrace();
	        	}
	        	ipAddress= inet.getHostAddress();   
	         }
        } 
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割   
        if(ipAddress!=null && ipAddress.length()>15){
        	//"***.***.***.***".length() = 15   
            if(ipAddress.indexOf(",")>0) {
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));   
            }   
        }   
        return ipAddress;
    }
    
    /**
     * 获取客户端端浏览器、操作系统名称等信息
     * @param request HTTP请求对象
     * @return 返回客户端信息
     */
    public static String getUserAgent(HttpServletRequest request) {
    	String userAgent = null;
    	if(null != request) {
    		userAgent = request.getHeader("user-agent");
    	}
    	return userAgent;
    }
}
